package org.yidu.novel.utils;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * <p>
 * 邮件工具类
 * </p>
 * Copyright(c) 2014-2017 YiDu-Novel. All rights reserved.
 * 
 * @version 2.0.0
 * @author shinpa.you
 */
@Component
public class MailUtils {
    /**
     * logger
     */
    protected static Log logger = LogFactory.getLog(MailUtils.class);

    @Value("${mail.smtp.username}")
    private static String username;
    @Value("${mail.smtp.password}")
    private static String password;
    @Value("${mail.smtp.auth}")
    private static boolean isSmtpAuth = false;
    @Value("${mail.smtp.starttls.enable}")
    private static boolean isStmpStarttlsEnable = false;
    @Value("${mail.smtp.host}")
    private static String smtpHost;
    @Value("${mail.smtp.port}")
    private static int smtpPort = 25;
    @Value("${mail.smtp.from}")
    private static String smtpFrom;

    /**
     * 发邮件处理
     * 
     * @param toAddr
     *            邮件地址
     * @param content
     *            邮件内容
     * @return 成功标识
     */
    public static boolean sendMail(String toAddr, String title, String content, boolean isHtmlFormat) {

        Properties props = new Properties();
        props.put("mail.smtp.auth", isSmtpAuth);
        props.put("mail.smtp.starttls.enable", isStmpStarttlsEnable);
        props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.port", smtpPort);

        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        try {
            Message message = new MimeMessage(session);
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddr));
            message.setSubject(title);
            if (isHtmlFormat) {
                message.setContent(content, "text/html");
            } else {
                message.setText(content);
            }
            Transport.send(message);

        } catch (MessagingException e) {
            logger.warn(e);
            return false;
        }
        return true;

    }

}
